package com.unique.demo.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.unique.ioc.annotation.Service;
import org.unique.support.orm.dao.SqlBase;
import org.unique.support.orm.exception.UpdateException;
import org.unique.support.orm.tx.annotation.Transactional;

import com.unique.demo.model.Person;
import com.unique.demo.service.PersonService;

@Service
public class PersonServiceImpl implements PersonService {

	private Logger logger = Logger.getLogger(PersonServiceImpl.class);
	
	@Override
	public Person get(Integer id) {
		return Person.db.findByPK(id);
	}

	@Override
	@Transactional
	public boolean save(String name, Integer age, Integer birthday, Integer status) {
		try {
			Person.db.insert("insert into t_person(name, age, birthday, status) values(?,?,?,?)", name, age, birthday, status);
			return true;
		} catch (UpdateException e) {
			logger.error("保存失败:" + e.getMessage());
		}
		return false;
	}

	@Override
	public boolean update(Integer id, String name, Integer age, Integer birthday) {
		SqlBase sql = SqlBase.update("update t_person");
		sql.set("name", name);
		sql.set("age", age);
		sql.set("birthday", birthday);
		sql.eq("id", id);
		try {
			Person.db.update(sql.getSQL(), name, age, birthday, id);
			return true;
		} catch (UpdateException e) {
			logger.error("更新失败:" + e.getMessage());
		}
		return false;
	}

	@Override
	public boolean delete(Integer id) {
		try {
			Person.db.deleteByPK(id);
			return true;
		} catch (UpdateException e) {
			logger.error("删除失败:" + e.getMessage());
		}
		return false;
	}

	@Override
	public List<Person> getList(String name, Integer status) {
		SqlBase base = SqlBase.select("select * from t_person");
		base.likeLeft("name", name).eq("status", status);
		return Person.db.findList(base.getSQL(), base.getParams());
	}

}
